package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements Runnable{
    private static final String TAG = "RateActivity";
    private float dollarrate;
    private float eurorate;
    private float wonrate;
    Handler handler;
    TextView show;
    String date,today;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show=(TextView) findViewById(R.id.hi);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        today = format1.format(new Date());  //获取今天的日期并转换成字符串
        Log.i(TAG, "Today'date" + today);
        //使用SharedPreferences保存数据，从myrate文件中读数据
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);

        dollarrate = sharedPreferences.getFloat("dollar_rate",0.0f);
        eurorate = sharedPreferences.getFloat("euro_rate",0.0f);
        wonrate = sharedPreferences.getFloat("won_rate",0.0f);
        date = sharedPreferences.getString("date","0000-00-00");
        //开启子线程
        //如果今天的日期与myrate中的更新日期不一致，则开启子线程
        Thread t = new Thread(this);
        t.start();
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==5 && !today.equals(date)) {
//                    String str = (String) msg.obj;
//                    Log.i(TAG, "handleMessage: getMessage msg = " + str);
//                    show.setText(str);
                    Bundle bdl = (Bundle) msg.obj;
                    dollarrate = bdl.getFloat("dollar-rate");
                    eurorate = bdl.getFloat("euro-rate");
                    wonrate = bdl.getFloat("won-rate");

                    Log.i(TAG, "handleMessage: dollarrate:" + dollarrate);
                    Log.i(TAG, "handleMessage: eurorate:" + eurorate);
                    Log.i(TAG, "handleMessage: wonrate:" + wonrate);
                    //更新myrate里面的汇率和日期值
                    SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);

                    SharedPreferences.Editor editor = sp.edit();
                    editor.putFloat("dollar_rate",dollarrate);
                    editor.putFloat("euro_rate",eurorate);
                    editor.putFloat("won_rate",wonrate);
                    editor.putString("date",date);
                    editor.apply();
                    Log.i(TAG, "onCreate: sp dollarRate=" + dollarrate);
                    Log.i(TAG, "onCreate: sp euroRate=" + eurorate);
                    Log.i(TAG, "onCreate: sp wonRate=" + wonrate);
                    Log.i(TAG, "onCreate: sp update=" + date);

                }
                super.handleMessage(msg);
            }
        };
    }

    public void click(View btn) {
        EditText input = findViewById(R.id.rmb);
        String s = input.getText().toString();
        if (s.length() == 0) {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_LONG).show();
            return;
        }
        String msg;
        Log.i(TAG, "click:进行计算");
        float inp = Float.parseFloat(s);
        float r = 0.0f;
        if (btn.getId() == R.id.euro)
            r = inp * dollarrate;
        else if (btn.getId() == R.id.dollar)
            r = inp * eurorate;
        else r = inp * wonrate;
        TextView result = findViewById(R.id.hi);
        result.setText(String.valueOf(r));
    }

    public void open(View btn) {
        Log.i(TAG, "open:打开新窗口");
        Intent config = new Intent(this, config.class);
        config.putExtra("dollar_rate_key", dollarrate);
        config.putExtra("euro_rate_key", eurorate);
        config.putExtra("won_rate_key", wonrate);
        Log.i(TAG, "open:dollarRate=" + dollarrate);
        Log.i(TAG, "open:euroRate=" + eurorate);
        Log.i(TAG, "open:wonRate=" + wonrate);

        //startActivity(config);
        startActivityForResult(config, 1);
    }

   // @Override
//    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
//        if(item.getItemId()==R.id.menu_set){
//           // openconfig();
//        }else if(item.getItemId()==R.id.open_list){
//            //打开列表窗口
//            Intent list =new Intent(this,MyList.class);
//            startActivity(list);
//        }
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == 2) {

            Bundle bundle = data.getExtras();
            dollarrate = bundle.getFloat("key_dollar", 0.1f);
            eurorate = bundle.getFloat("key_euro", 0.1f);
            wonrate = bundle.getFloat("key_won", 0.1f);
            Log.i(TAG, "onActivityResult: dollarRate=" + dollarrate);
            Log.i(TAG, "onActivityResult: euroRate=" + eurorate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonrate);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    public void run() {
        Log.i(TAG, "run: run()......");
        for(int i=1;i<=3;i++){
            Log.i(TAG, "run: i=" + i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //获取Msg对象，用于返回主线程
//        Message msg = handler.obtainMessage(5); //msg.what = 5;
//        msg.obj = "Hello from run()";
//        handler.sendMessage(msg);
        //获取网络数据
//        URL url = null;
//        try {
//            url = new URL("http://www.usd-cny.com/icbc.htm");
//            HttpURLConnection http = (HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//
//            String html = inputStream2String(in);
//            Log.i(TAG, "run: html=" + html);
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Bundle bundle = new Bundle();
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();  //document必须选择jsoup版
            Log.i(TAG, "run: title" + doc.title());
            Element table = doc.getElementsByTag("table").first();
//            Log.i(TAG, "run: table=" + table);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);
            for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                if(tds.size()>0){
                    //提取数据
                    Element td1 = tds.first(); //名城
                    Element td2 = tds.last();  //汇率值
                    Log.i(TAG,"run" + td1.text() + "-->" + td2.text());
                    String str = td1.text();  //!!将td1也要转成字符否则无法识别
                    String r = td2.text(); //将td2转成String类型

                    float rate = Float.parseFloat(r);
                    //将值传入bundle
                    if("美元".equals(str)){
                        bundle.putFloat("dollar-rate", rate);
                    }else if("欧元".equals(str)){
                        bundle.putFloat("euro-rate", rate);
                    }else if("韩元".equals(str)){
                        bundle.putFloat("won-rate", rate);
                    }
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                date = format.format(new Date());  //获取更新时间
                Message msg = handler.obtainMessage(5);
                msg.obj = bundle;
                handler.sendMessage(msg);
            }

        }  catch (IOException e) {
            e.printStackTrace();
        }

        }
    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");//用gb2312的规则转换成字符串
        while (true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}